package com.entfrm.base.util;

import cn.hutool.core.io.resource.ClassPathResource;
import cn.hutool.core.net.NetUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.http.HtmlUtil;
import com.entfrm.base.config.GlobalConfig;
import com.entfrm.base.exception.BaseException;
import lombok.extern.slf4j.Slf4j;
import org.lionsoul.ip2region.xdb.Searcher;

import java.io.File;

/**
 * @author yong
 * @date 2019/6/12
 * @description 根据IP地址获取城市
 */
@Slf4j
public class AddressUtil {

    private static final Searcher SEARCHER;

    static {
        String fileName = "ip2region.xdb";
        File existFile = FileUtil.file(GlobalConfig.getProfile() + fileName);
        if (!FileUtil.exist(existFile)) {
            ClassPathResource fileStream = new ClassPathResource(fileName);
            if (ObjectUtil.isEmpty(fileStream.getStream())) {
                throw new BaseException("AddressUtil初始化失败，原因：IP地址库数据不存在！");
            }
            FileUtil.writeFromStream(fileStream.getStream(), existFile);
        }

        String dbPath = existFile.getPath();

        // 1、从 dbPath 加载整个 xdb 到内存。
        byte[] cBuff;
        try {
            cBuff = Searcher.loadContentFromFile(dbPath);
        } catch (Exception e) {
            throw new BaseException("AddressUtil初始化失败，原因：从ip2region.xdb文件加载内容失败！" + e.getMessage());
        }
        // 2、使用上述的 cBuff 创建一个完全基于内存的查询对象。
        try {
            SEARCHER = Searcher.newWithBuffer(cBuff);
        } catch (Exception e) {
            throw new BaseException("AddressUtil初始化失败，原因：" + e.getMessage());
        }
    }

    /**
     * 根据IP地址离线获取城市
     */
    public static String getCityInfo(String ip) {
        if (StrUtil.isBlank(ip)) {
            return "XX XX";
        }
        ip = ip.trim();
        // 内网不查询
        ip = StrUtil.contains(ip, "0:0:0:0:0:0:0:1") ? "127.0.0.1" : HtmlUtil.cleanHtmlTag(ip);
        if (NetUtil.isInnerIP(ip)) {
            return "内网IP";
        }
        try {
            // 执行查询
            String region = SEARCHER.search(ip);
            return region.replace("0|", "").replace("|0", "");
        } catch (Exception e) {
            log.error("IP地址离线获取城市异常 {}", ip);
            return "未知";
        }
    }

    public static void main(String[] args) {

        System.out.println(getCityInfo("115.218.10.198"));
    }
}
